/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package unc.pds.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Enumeration;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import unc.pds.data.Consts;
import unc.pds.service.RegisterRemote;
import unc.pds.service.RegisterRemoteHome;
import unc.pds.service.ServiceBeanRemote;
import unc.pds.service.ServiceBeanRemoteHome;
import unc.pds.util.Arch;
import unc.pds.util.ArchImpl;

/**
 *
 * @author Михаил
 */
public class RegisterServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (!request.getParameter("captcha").toUpperCase().equals(request.getSession().getAttribute("captcha").toString().toUpperCase())) {
                Enumeration list = request.getParameterNames();
                String addition = "";
                while (list.hasMoreElements()) {
                    String next = (String)list.nextElement();
                    if (!(next.equals("password")||next.equals("captcha"))) {
                        addition += "&"+next+"="+URLEncoder.encode(request.getParameter(next),"UTF-8");
                    }
                }
                response.sendRedirect("register.jsp?redirect=captcha"+addition);
            } else {
                RegisterRemote registerBean = ((RegisterRemoteHome) (new InitialContext()).lookup("ejb/Register")).create();
                Arch doc = new ArchImpl("root", "null");
                doc.addChild(new ArchImpl(Consts.ATTR__USER_NICKNAME, request.getParameter("login")));
                doc.addChild(new ArchImpl(Consts.ATTR__USER_PASSWORD, request.getParameter("password")));
                Long sid = registerBean.register(doc);
                request.getSession().setAttribute("sid", sid);
                ServiceBeanRemote service = ((ServiceBeanRemoteHome) (new InitialContext()).lookup("ejb/ServiceBean")).create(sid);
                response.sendRedirect("index.jsp?id=" + service.getUser().getKey() + "&view=posts");
            }
        } catch (Exception e) {
            if (e.getCause().getCause() instanceof unc.pds.exc.UserAlreadyExistException) {
                Enumeration list = request.getParameterNames();
                String addition = "";
                while (list.hasMoreElements()) {
                    String next = (String)list.nextElement();
                    if (!(next.equals("password")||next.equals("captcha")||next.equals("login"))) {
                        addition += "&"+next+"="+URLEncoder.encode(request.getParameter(next),"UTF-8");
                    }
                }
                response.sendRedirect("register.jsp?redirect=alreadyexists"+addition);
            } else {
                response.sendError(500);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
